package com.itheima.task;

import com.itheima.config.AliOssProperties;
import com.itheima.common.constant.RedisConstant;
import com.itheima.common.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author Encounter
 * @date 2024/10/09 18:41<br/>
 */
@Component
@Slf4j
public class UploadTask
    {
        @Autowired
        private RedisTemplate<String, String> redisTemplate;
        @Autowired
        private AliOssUtil aliOssUtil;
        @Autowired
        private AliOssProperties aliOssProperties;
        
        //每天凌晨一点执行
        @Scheduled(cron = "0 0 1 * * ?")
        //测试使用，每分钟执行一次
        //@Scheduled(cron = "0/60 * * * * ? ")
        public void cleanJunkPictures()
            {
                log.info("开始清理垃圾图片...");
                SetOperations<String, String> setOperations = redisTemplate.opsForSet();
                //进行差集运算，结果只包含元素
                Set<String> junkPictures = setOperations.difference(RedisConstant.SETMEAL_PIC_RESOURCES, RedisConstant.SETMEAL_PIC_DB_RESOURCES);
                //log.info("差集：{}", junkPictures);
                //遍历垃圾图片集合，开始清除
                if (junkPictures != null && !junkPictures.isEmpty())
                    {
                        //因为存储的在同一个bucket中，所以只获取一次即可
                        String endpoint = aliOssProperties.getEndpoint();
                        String bucketName = aliOssProperties.getBucketName();
                        int count = 0;
                        for (String junkPicture : junkPictures)
                            {
                                System.out.println(junkPicture);
                                //redis中存储的是文件完整路径，把文件名前面的路径部分替换为空字符串得到的就是原图片名
                                String picName = junkPicture.replace("https://" + bucketName + "." + endpoint + "/", "");
                                
                                //开始执行aLiOssUtil中定义的删除方法
                                log.info("当前删除的图片：{}", picName);
                                aliOssUtil.delete(picName);
                                count++;
                            }
                        
                        //把redis中的垃圾图片路径全部删除
                        setOperations.remove(RedisConstant.SETMEAL_PIC_RESOURCES, junkPictures.toArray());
                        log.info("成功清理{}张图片", count);
                    }
                else
                    {
                        log.info("很干净，没有垃圾图片");
                    }
            }
    }
